package com.ts.api.module.api.controller;

import com.gitee.apanlh.annotation.viewresolver.RequestParamVo;
import com.gitee.apanlh.util.algorithm.digest.MD5;
import com.gitee.apanlh.util.reflection.ClassConvertUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.gitee.apanlh.web.model.vo.ResultVO;
import com.ts.api.module.api.convert.infoflow.handler.ApiInfoFlowHandler;
import com.ts.api.module.api.entity.ApiUserRequest;
import com.ts.api.module.api.entity.po.ApiKeyPO;
import com.ts.api.module.api.entity.vo.ReqGuangDianTongVO;
import com.ts.api.module.api.service.ApiInfoFlowService;
import com.ts.api.module.api.service.ApiRequestValidateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *  信息流渠道
 *
 *  @author Pan
 */
@RestController
@RequestMapping("/data/api/flow")
public class ApiInfoFlowController {

    @Autowired
    private ApiRequestValidateService apiRequestValidateService;
    @Autowired
    private ApiInfoFlowHandler apiInfoFlowHandler;
    @Autowired
    private ApiInfoFlowService apiInfoFlowService;

    /**
     *  广点通
     *
     *  @param  apiClientId API客户端id
     *  @param  requestVO   请求对象
     *  @return ResultVO
     */
    @PostMapping("/gdt/{apiClientId}")
    public ResultVO<Object> gdt(@PathVariable String apiClientId, @RequestParamVo RequestVO requestVO) {
        //  验证是否属于正确API渠道
        ApiKeyPO apiKeyPO = apiRequestValidateService.validClient(apiClientId);

        //  获取广点通对象
        ReqGuangDianTongVO gdtVO = requestVO.toBean(ReqGuangDianTongVO.class);
        gdtVO.setApiClientId(apiClientId);
        String bundle = requestVO.getStr("bundle");
        gdtVO.setBundle(bundle);

        //  转化ApiUserInfo对象
        ApiUserRequest apiUserRequest = apiInfoFlowHandler.convert(gdtVO);
        apiUserRequest.setApiClientId(apiKeyPO.getApiClientId());
        apiUserRequest.setLoanChannelId(apiKeyPO.getLoanChannelId());
        apiUserRequest.setPhoneMd5(MD5.create().digestToHex(apiUserRequest.getPhone()));
        //  限制年龄
        String age = apiUserRequest.getAge();
        if (ValidParam.isNotEmpty(age)) {
            if (ClassConvertUtils.toInt(age) > 70) {
                apiUserRequest.setAge("30");
            }
        }
        //  分发
        apiInfoFlowService.allocate(apiKeyPO, apiUserRequest, true);
        return ResultVO.suc("下发成功");
    }
}
